package edu.ccut.saturn.studio.logic.contextaction;

import java.util.List;

import org.eclipse.gef.ui.actions.Clipboard;
import org.eclipse.gef.ui.actions.SelectionAction;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.ActionFactory;

import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.logic.model.Shape;
import edu.ccut.saturn.studio.logic.parts.ShapeEditPart;

public class CopyAction extends SelectionAction {
	
	public CopyAction(IWorkbenchPart part) {
		super(part);
		setId(ActionFactory.COPY.getId());
		setText(Messages.getString("CopyAction.copy"));   //$NON-NLS-1$
	}

	@SuppressWarnings("unchecked") 
	@Override
	protected boolean calculateEnabled() {
		List<Object> objects = this.getSelectedObjects();
		for(Object object : objects){
			if(object instanceof ShapeEditPart){
				ShapeEditPart part = (ShapeEditPart)object;
				if(isSubclass(Shape.class, part.getModel().getClass())){
					return true;
				}
			}
		}
		return false;
	}
	
	public void run() {
		Clipboard.getDefault().setContents(super.getSelectedObjects());
	}
	
	private boolean isSubclass(Class<?> baseClass, Class<?> subClass) {
		Class<?> subBase = subClass;

		do {
			subBase = subBase.getSuperclass();

			if (subBase == baseClass) {
				return true;
			}
		} while (subBase != null);

		return false;
	}
}
